import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import log from 'src/common/utils/log';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest();
    const method = request.method;
    const url = request.url;
    const now = Date.now();

    log.info(`[Request] ${method} ${url}`);
    log.info(`[Params] Query:`, request.query);
    if (url !== '/game/save') {
      log.info(`[Params] Body:`, request.body);
    }

    return next.handle().pipe(
      tap((data) => {
        const response = context.switchToHttp().getResponse();
        const delay = Date.now() - now;
        log.info(
          `[Response] ${method} ${url} ${response.statusCode} - ${delay}ms`,
        );
        // log.debug(`[Response Data]`, data);
      }),
    );
  }
}
